package com.capgemini.orf.dao;

import java.util.List;

import javax.persistence.EntityManager;

import com.capgemini.orf.datamodel.Customer;

public class CustomerDao {

	public Customer getCustomerById(long id) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			return em.find(Customer.class, id);
		} finally {
			em.close();
		}
	}

	public List<Customer> getCustomersByName(String customerName) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			@SuppressWarnings("unchecked")
			List<Customer> customers = em.createQuery("SELECT FROM Customer WHERE uppercaseName LIKE :customerName")
					.setParameter("customerName", customerName.toUpperCase() + "%").getResultList();
			// fetch the list eagerly by invoking the method 'size' on it
			customers.size();
			return customers;
		} finally {
			em.close();
		}
	}

	public void save(Customer customer) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			em.persist(customer);
		} finally {
			em.close();
		}
	}
}
